package controller

import (
	"fmt"
	base "nonius/base/controllers"
	"nonius/services"

	"nonius/forms"
)

type UserController struct {
	base.RequiredAuthController
}

func (c *UserController) Add() {

	if c.Ctx.Input.IsPost() {
		var form forms.UserForm
		c.ParseForm(&form)
		services.AddUser(form.Name, form.Password, form.Addr, form.Sex)
		c.Redirect("/user/query", 302)
	} else if c.Ctx.Input.IsGet() {
		c.TplName = "user/add.html"
	}
}

func (c *UserController) Query() {

	c.Data["users"] = services.GetUsers()
	fmt.Println(services.GetUsers())
	c.TplName = "user/user.html"

}

func (c *UserController) Edit() {

	if c.Ctx.Input.IsGet() {
		id, _ := c.GetInt64("id")
		c.Data["ID"] = id
		user := services.GetUser(id)
		c.Data["user"] = user
		fmt.Println(id)
		c.TplName = "user/edit.html"
	} else if c.Ctx.Input.IsPost() {
		// var id int64
		// c.GetInt64("id")
		var form forms.UserForm
		if err := c.ParseForm(&form); err == nil {
			services.EditUser(form.ID, form.Name, form.Addr, form.Sex)
			fmt.Println(form)
		}

		c.Redirect("/user/query", 302)
	}

}

func (c *UserController) Delete() {

	var id int64
	if err := c.Ctx.Input.Bind(&id, "id"); err == nil {
		services.DelUser(id)
	}
	c.Redirect("/user/query", 302)

}
